<template>
	<div>
		<p>验本地Login模块</p>
		<x-input
			placeholder="手机号码"
			is-type="china-mobile"
			v-model="tel">
			<x-button :mini="true" slot="right" @click.native="evt_sendCode">发送验证码</x-button>
		</x-input>
		<x-input placeholder="输入验证码" v-model="code"></x-input>
		<x-button @click.native="evt_doLogin">登录</x-button>
		<x-button type="primary" :mini="true" @click.native="evt_checkLogin">检查登录</x-button>
		<x-button @click.native="evt_logout">注销登录</x-button>
		<span>{{User}}</span>
	</div>
</template>
<script type="text/javascript">
	import Vue from 'vue'
	import { XButton, XInput } from 'vux'
	import { mapState, mapActions } from 'vuex'

	import { isLogined } from '@/service/checkUserLogin'
	import { SendCodeModel, LoginMobileModel } from '@/model/com.model'
	import storage from '@/localstorage/conf'
	import * as Acts from '@/store/consts'

	let infoKey = storage.user;

	export default {
		name: 'demo-login',
		data: () => {
			return {
				tel: '',
				code: ''
			}
		},
		computed: {
			...mapState(['User'])
		},
		created() {
			this.SendCodeModel = new SendCodeModel();
			this.LoginMobileModel = new LoginMobileModel();
			this.SendCodeModel.setUrl();
			this.LoginMobileModel.setUrl();
		},
		methods: {
			// {id, mobile}
			setLocalUserInfo(data) {
				Vue.ls.set(infoKey, data);
			},
			removeLocalUserInfo() {
				Vue.ls.remove(infoKey);
			},
			evt_sendCode() {
				if (this.tel) {
					this.SendCodeModel
					.setParams({
						mobile: this.tel
					})
					.go()
					.then(res => {
						this.$vux.toast('验证码已发送');
						// console.log(res);
					})
					.catch(err => {
						console.log(err);
					});
				}
			},
			evt_doLogin() {
				this.LoginMobileModel
				.setParams({
					mobile: this.tel,
					code: this.code
				})
				.go()
				.then(res => {
					// 设置vuex的值
					this[Acts.SET_USER_INFO](res.data);
					// 设置本地存储的值
					this.setLocalUserInfo(res.data);
				})
				.catch(err => {
					this.$vux.toast.text(err.msg);
				})
			},
			evt_logout() {
				this[Acts.SET_USER_INFO]({id: null, mobile: ''});
				this.removeLocalUserInfo();
			},
			evt_checkLogin() {
				if (isLogined()) {
					this.$vux.toast.text('已登录');
				} else {
					this.$vux.toast.show({
						text: '未登录',
						type: 'text',
						position: 'top',
						isShowMask: true,
						onHide: () => {
							this.$router.push({
								name: 'home_login',
								query: {
									from: this.$route.name
								}
							})
						}
					});
				}
			},
			...mapActions([Acts.SET_USER_INFO])
		},
		components: {
			XButton,
			XInput
		}
	}
</script>